﻿package net.wangit.view.element;

import java.util.HashMap;
import java.util.Map;

public class ElementExtendedAttribute {

	private int currentRowIndex;
	private Map rows;

	public ElementExtendedAttribute() {
		currentRowIndex = -1;
		rows = new HashMap();
	}

	public void move(int beginRowIndex, int endRowIndex) {
		for (int i = endRowIndex; i >= beginRowIndex; i--) {
			String key = Integer.toString(i);
			Map row = (Map) rows.get(key);
			if (row != null) {
				rows.put(Integer.toString(i + 1), row);
				rows.put(key, null);
			}
		}

	}

	public void setCurrentRowIndex(int currentRowIndex) {
		this.currentRowIndex = currentRowIndex;
	}

	public void set(int i, String name, Object object) {
		addRow(i).put(name, object);
	}

	public void set(int i, String name, int value) {
		set(i, name, Integer.toString(value));
	}

	public void set(int i, String name, boolean value) {
		set(i, name, Boolean.toString(value));
	}

	public Object getObject(String name, Object defaultObject) {
		if (currentRowIndex < 0) {
			return defaultObject;
		} else {
			Object object = get(name);
			return object != null ? object : defaultObject;
		}
	}

	public String getString(String name, String defaultValue) {
		if (currentRowIndex < 0) {
			return defaultValue;
		} else {
			Object value = get(name);
			return value != null ? (String) value : defaultValue;
		}
	}

	public int getInt(String name, int defaultValue) {
		if (currentRowIndex < 0) {
			return defaultValue;
		} else {
			Object value = get(name);
			return value != null ? Integer.parseInt((String) value)
					: defaultValue;
		}
	}

	public boolean getBoolean(String name, boolean defaultValue) {
		if (currentRowIndex < 0) {
			return defaultValue;
		} else {
			Object value = get(name);
			return value != null ? Boolean.getBoolean((String) value)
					: defaultValue;
		}
	}

	private Object get(String name) {
		Map row = (Map) rows.get(Integer.toString(currentRowIndex));
		return row != null ? row.get(name) : null;
	}

	private Map addRow(int rowIndex) {
		String key = Integer.toString(rowIndex);
		Map row = (Map) rows.get(key);
		if (row == null) {
			row = new HashMap();
			rows.put(key, row);
		}
		return row;
	}
}
